package com.fit.pages.vehicle;

import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.util.EnumSelectModel;

import com.fit.annotations.AdminAccess;
import com.fit.annotations.UserAccess;
import com.fit.dao.vehicle.VehicleDAO;
import com.fit.entities.Vehicle;
import com.fit.model.type.VehicleType;

@UserAccess
@AdminAccess
public class InsertVehicle {

	@Property
	@SessionState(create = false)
	private Vehicle vehicle;

	@Inject
	private VehicleDAO vehicleDAO;

	@Inject
	private Messages messages;
	
	@Component
	private Form createForm;

	@Persist
	@Property
	private String error;

	@Persist
	@Property
	private String confirmation;
	
	@Property
	@Persist
	private VehicleType vehicleType;
	
	public SelectModel getTypes() {
		return new EnumSelectModel(VehicleType.class, messages);
	}
	
	void onPrepare() {
		vehicle = new Vehicle();
	}

	Object onSubmitFromCreateForm() {
		error = "";
		confirmation="";
		Vehicle temp = vehicleDAO.findByChassisNumber(vehicle
				.getChassisNumber());

		if (temp == null) {
			if (vehicleType == null) {
				error = "You didn't choose vehicle type!";
				return null;
			}
			vehicle.setTypeOfVehicle(vehicleType.toString());
			if (vehicleDAO.save(vehicle)) {
				confirmation = "Vehicle successfully inserted!";
				return null;
			}
			confirmation = "Vehicle is null!";
			return null;
		}

		error = "Car with chassis number "
				+ vehicle.getChassisNumber() + " already exists!";

		return null;
	}

	@OnEvent(component = "ResetConfLink")
	Object onResetConfLink() {
		confirmation = "";
		return null;
	}

	@OnEvent(component = "ResetErrorLink")
	Object onResetErrorLink() {
		error = "";
		return null;
	}

	public boolean isErrorNotNull() {
		if (error == null || error == "") {
			return false;
		}
		return true;
	}

	public boolean isConfirmationNotNull() {
		if (confirmation == null || confirmation == "") {
			return false;
		}
		return true;
	}

}
